package com.apache.passport.aop;

import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.cache.util.Validator;
import com.apache.passport.entity.LoginInfo;
import org.apache.log4j.Logger;
import org.springframework.aop.AfterReturningAdvice;

import java.lang.reflect.Method;

/**
 * description: 登录信息方法后拦截
 *
 * @author Hou Dayu 创建时间：2016-12-19
 */
public class LoginMethodAfterAdvice implements AfterReturningAdvice {

    private Logger log = Logger.getLogger(LoginMethodAfterAdvice.class);

    /**
     * description:  将用户信息写入到文件中,5M为一个文件
     *
     * @param loginInfo
     * @return
     */
    private LoginInfo getLoginInfo(LoginInfo loginInfo) {
        if (Validator.isEmpty(loginInfo)) {
            return null;
        }
        return loginInfo;
    }

    /**
     * returnValue 返回值
     * TODO target:方法执行的结果.
     * 执行将用户登录日志写入数据库的操作
     *
     * @see org.springframework.aop.AfterReturningAdvice#afterReturning(java.lang.Object, java.lang.reflect.Method, java.lang.Object[], java.lang.Object)
     */
    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target)
            throws Throwable {
        String targetName = target.getClass().getName();
        String methodName = method.getName();
        if (targetName.indexOf("com.apache.passport") != -1) {
            if (null != args && args.length > 0) {
                try {
                    ParamsVo arguments = (ParamsVo) args[0];
                    if ("execute".equals(methodName) && "true"
                            .equals(String.valueOf(returnValue))) {
                        boolean mark = false;
                        if (returnValue instanceof ResultEntity) {
                            mark = true;
                        } else if ("true".equals(String.valueOf(returnValue))) {
                            mark = true;
                        }
                        if (mark) {
                            LoginInfo logInfo = getLoginInfo(
                                    (LoginInfo) arguments.getParams("loginInfo"));
                            if (!Validator.isEmpty(logInfo)) {
                                LoginAopRunable runnable = new LoginAopRunable(logInfo);
                                PassportTheardPool.getInstance().saveLogger(runnable);
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error(e);
                }
            }
        }
    }
}
